import JSEncrypt from 'jsencrypt'
import CryptoJS from 'crypto-js'

let rsa = function(publicKey, str) {
  const encrypt = new JSEncrypt()
  // 设置公钥
  encrypt.setPublicKey(publicKey)
  const e = encrypt.encrypt(str)
  return e
}
// 默认的 KEY 与 iv 如果没有给
const KEY = CryptoJS.enc.Utf8.parse('1234567890123456')
const IV = CryptoJS.enc.Utf8.parse('1234567890123456')

/**
 * AES加密 ：字符串 key iv  返回base64
 */
let encrypt = function(word, keyStr, ivStr) {
  let key = KEY
  let iv = IV
  if (keyStr) {
    key = CryptoJS.enc.Utf8.parse(keyStr)
    iv = CryptoJS.enc.Utf8.parse(ivStr)
  }

  const srcs = CryptoJS.enc.Utf8.parse(word)
  const encrypted = CryptoJS.AES.encrypt(srcs, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.ZeroPadding
  })
  // console.log("-=-=-=-", encrypted.ciphertext)
  return CryptoJS.enc.Base64.stringify(encrypted.ciphertext)
}
/**
 * AES 解密 ：字符串 key iv  返回base64
 *
 */
let decrypt = function(word, keyStr, ivStr) {
  let key = KEY
  let iv = IV

  if (keyStr) {
    key = CryptoJS.enc.Utf8.parse(keyStr)
    iv = CryptoJS.enc.Utf8.parse(ivStr)
  }

  const base64 = CryptoJS.enc.Base64.parse(word)
  const src = CryptoJS.enc.Base64.stringify(base64)

  const decrypt = CryptoJS.AES.decrypt(src, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.ZeroPadding
  })

  const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
  return decryptedStr.toString()
}

let copy = function(obj) {
  return JSON.parse(JSON.stringify(obj))
}
let isEmpty = function(str) {
  return str == null || str.length === 0 || str === ''
}

let isBlank = function(str) {
  return str == null || str.length === 0 || (str + '').trim() === ''
}
let isNotBlank = function(str) {
  return !isBlank(str)
}
/**
 * 参数处理
 * @param {*} params  参数
 */
let tansParams = function(params) {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName]
    const part = encodeURIComponent(propName) + '='
    if (value !== null && value !== '' && typeof (value) !== 'undefined') {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== '' && typeof (value[key]) !== 'undefined') {
            const params = propName + '[' + key + ']'
            const subPart = encodeURIComponent(params) + '='
            result += subPart + encodeURIComponent(value[key]) + '&'
          }
        }
      } else {
        result += part + encodeURIComponent(value) + '&'
      }
    }
  }
  return result
}
/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
let handleTree = function(data, id, parentId, children) {
  const config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children'
  }

  const childrenListMap = {}
  const nodeIds = {}
  const tree = []

  for (const d of data) {
    const parentId = d[config.parentId]
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = []
    }
    nodeIds[d[config.id]] = d
    childrenListMap[parentId].push(d)
  }

  for (const d of data) {
    const parentId = d[config.parentId]
    if (nodeIds[parentId] == null) {
      tree.push(d)
    }
  }

  for (const t of tree) {
    adaptToChildrenList(t)
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]]
    }
    if (o[config.childrenList]) {
      for (const c of o[config.childrenList]) {
        adaptToChildrenList(c)
      }
    }
  }
  return tree
}

let removeArrObj = function(arr,o) {
  let i = arr.indexOf(o)
  if(i>-1){
    arr.splice(i,1)
  }
}

let pushArray = function(arr,arr2) {
  if(arr instanceof Array && arr2 instanceof Array){
    for(let i = 0;i < arr2.length;i++){
      arr.push(arr2[i])
    }
  }
}

let fmtEditorHtml = function(html) {
  if(html){
    html = html.replaceAll(/<[/]?p[^>]*>/g,'')
    if(html === '<br/>' || html === '<br>'){
      html = ''
    }
  }
  return html
}


export default {
  rsa,encrypt,decrypt,copy,isEmpty,isBlank,isNotBlank,tansParams,handleTree,removeArrObj,fmtEditorHtml,pushArray
}

